module BtnSwitchLED (
        input sys_clk,
        input sys_rst_n,
        input [1:0] keys,
        // 刚启动时保持全灭
        output reg [1:0] led = 2'b00
    );

    // 50MHz的频率下,0.5s的计数值
    parameter MaxCount = 32'd25_000_000-32'd1;
    // 按键保持时间,达到该时间才认为按下
    parameter KeyHoldTime = 32'd10_000;

    // 当前的计数值
    reg [31:0] cnt;
    // 当前的状态,0时全暗,1时流水,2时同亮同灭
    reg [1:0] state;

    // 按键的保持时间
    reg [31:0] key_hold_time;

    // 计数值变化
    always @(negedge sys_rst_n or posedge sys_clk) begin
        if(!sys_rst_n) begin
            cnt <= 32'd0;
        end
        else if(cnt>=MaxCount) begin
            // 到了时间则重置
            cnt <= 32'd0;
        end
        else begin
            // 没到则递增
            cnt <= cnt + 32'd1;
        end
    end

    // LED状态变化
    always @(negedge sys_rst_n or posedge sys_clk) begin
        if(!sys_rst_n) begin
            led <= 2'b00;
        end
        else begin
            case (state)
                2'd0:
                    led <= 2'b00;
                2'd1: begin
                    if(led==2'b00 || led==2'b11)
                        led <= 2'b10;
                    else if(cnt==MaxCount)
                        led <= {led[0], led[1]};
                    else
                        led<=led;
                end
                2'd2: begin
                    if(led==2'b01 || led==2'b10)
                        led <= 2'b00;
                    else if(cnt==MaxCount)
                        led <= ~led;
                    else
                        led <= led;
                end
                default:
                    led <= 2'b00;
            endcase
        end
    end

    // 状态变化
    always @(negedge sys_rst_n or posedge sys_clk) begin
        if(!sys_rst_n) begin
            // 复位时重置
            state <= 2'd0;
            key_hold_time <= 32'd0;
        end
        else
        case (keys)
            2'b01: begin
                key_hold_time <= key_hold_time + 32'd1;
                if(key_hold_time >= KeyHoldTime) begin
                    // 1时流水
                    state <= 2'd1;
                end
            end
            2'b10: begin
                key_hold_time <= key_hold_time + 32'd1;
                if(key_hold_time >= KeyHoldTime) begin
                    // 2时同亮同灭
                    state <= 2'd2;
                end
            end
            default: begin
                state <= state;
                key_hold_time <= 32'd0;
            end
        endcase
    end

endmodule
